<?php

namespace app\api\controller\app;

use app\admin\model\Coinorder;
use app\admin\model\Org;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shoporder;
use app\admin\model\Shopstaff;
use app\admin\model\Userbalance;
use app\admin\model\Usercoin;
use app\admin\model\Usercoinout;
use app\admin\model\Usercoupon;
use app\admin\model\Usermno;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;
use function EasyWeChat\Kernel\Support\get_client_ip;


class Game extends Api
{
    protected $noNeedLogin = ['extractGoldNum','extractGoldNumCheck','settleGoldNum','sxfOrderCallback'];
    protected $noNeedRight = '*';

    protected $app = null;
    protected $key = "AES0324HGLC5D030";


    public function addOrder()
    {

        $amount = $this->request->param('amount');
        $device_id = $this->request->param('device_id');
        $coinOrderModel = new Coinorder();

        if($amount == 5){
            $amount = 0.1;
        }

        $deviceModel = new \app\admin\model\Device();
        $device = $deviceModel->where('device_id',$device_id)->find();
        $userMnoModel = new Usermno();
        $userMno = $userMnoModel->where('user_id',$device['agent_id'])->where('is_trade',1)->find();
        if(!$userMno) $this->error("支付商户号未配置，请联系平台运营");

        $user = $this->auth->getUser();
        $order_no = getOrderSn();
        $db = array();
        $db['mno'] = $userMno['mno'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $order_no;
        $db['create_time'] = time();
        $db['device_id'] = $device_id;
        $db['amount'] = $amount;

        $id = $coinOrderModel->insertGetId($db);
        if($id>0){

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/game/sxfOrderCallback";

            $fs = array();
//                $realPay = formatMoney($pay_price- $pay_price*0.006);
//                foreach ($listMnos as $key=>$val){
//                    //走分账
//                    $fusruleId = array();
//                    $fusruleId['mno'] = $val['mno'];
//                    $fusruleId['allotValue'] = formatMoney($val['ratio']*$realPay/100);
//                    $fs[] = $fusruleId;
//
//                }
//
//                $req['fusruleId'] = $fs;

            $userWxModel = new Userweixin();
            $wx = $userWxModel->where('user_id',$user['id'])->find();
            $req['mno'] = $userMno['mno'];
            $req['ordNo'] =  $db['order_no'];
            $req['amt'] = $amount;

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = "wx763ae61820ee8dc5";
            $req['userId'] = $wx['openid'];

            $req['subject'] = "商品购买";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);

            error_log("===fz==".$res);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $db['order_no'];
                $info['payInfo'] = $result['respData'];
                $this->success('',$info);
            } else {
                $this->error($bizMsg);
            }
        }else{
            $this->error("充值订单生成失败");
        }

    }



    public function sxfOrderCallback()
    {
        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $coinOrderModel = new Coinorder();
            $order = $coinOrderModel->where('order_no',$out_trade_no)->find();
            $coinOrderModel->where('id',$order['id'])->update(['status'=>'payed']);
            $msgKey = "coin_charge_" . $order['id'];
            $deviceModel = new \app\admin\model\Device();
            $device = $deviceModel->where('device_id',$order['device_id'])->find();
            $isCount = $this->redis->get($msgKey);
            if (!$isCount) {

                $coin = $order['amount']*1000;
                $userCoinModel = new Usercoin();

                $dbCoin = $userCoinModel->where('user_id',$order['user_id'])->where('shop_id',$device['agent_id'])->find();
                if(!$dbCoin){
                    $userCoinModel->insert(['user_id'=>$order['user_id'],'shop_id'=>$device['agent_id'],'coin'=>$coin]);
                }else{
                    $userCoinModel->where('id',$dbCoin['id'])->setInc('coin',$coin);

                }
            }

        }
    }


    public function getGameUrl()
    {

        $gameUrl = "https://game.50xue.com/bird-hunting/";
        $device_id = $this->request->param('device_id');
        $user = $this->auth->getUser();
        $captcha = mt_rand(100000, 999999);


        $deviceModel = new \app\admin\model\Device();
        $device = $deviceModel->where('device_id',$device_id)->find();
        if(!$device) $this->error("设备不存在");
        $isHave = $this->redis->get($user['mobile']);
        if($isHave){
            $req = json_decode($isHave,true);
        }else{
            $req = array();
            $req['userId'] = $user['mobile']."";
            $req['shopId'] = $device['agent_id']."";
            $req['deviceId'] = $device_id."";
            $req['captcha'] = $captcha."";
            $this->redis->set($user['mobile'],json_encode($req));
        }
        error_log("====req====".json_encode($req));
        $token =  base64_encode(openssl_encrypt(json_encode($req), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA));

        error_log("=====token===".$token);
        $gameUrl = $gameUrl."?token=".$token;

        $ret['token'] = $token;
        $ret['url'] = $gameUrl;
        $this->success('',$ret);
    }

    public function extractGoldNum()
    {
        $token = $this->request->param('token');

        $result = openssl_decrypt(base64_decode($token), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);


        $result = json_decode($result,true);
        $mobile = $result['userId'];
        $deviceId = $result['deviceId'];
        $captcha = $result['captcha'];
        $shopId = $result['shopId'];
        $isHave = $this->redis->get($mobile);
        $ret = array();
//        if(!$isHave){
//            $ret['state'] = 1;
//            $ret['msg'] = "缓存不存在不能提取";
//            $ret['goldNum'] = 0;
//            $ret['lockId'] = "-1";
//            echo json_encode($ret);
//            die(-1);
//        }
//        $cacheToken =  base64_encode(openssl_encrypt($isHave, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA));
//        if($cacheToken != $token) {
//            $ret['state'] = 1;
//            $ret['msg'] = "token不一致";
//            $ret['goldNum'] = 0;
//            $ret['lockId'] = "-1";
//            echo json_encode($ret);
//            die(-1);
//        }

        $isLock = $this->redis->get($mobile);
        if($isLock){
            $ret['state'] = 1;
            $ret['msg'] = "15s内不可重复提取";
            $ret['goldNum'] = 0;
            $ret['lockId'] = "-1";
            echo json_encode($ret);
            die(-1);
        }
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->find();

        $userCoinModel =  new Usercoin();
        $coin = 0;
        $dbCoin  = $userCoinModel->where('user_id',$user['id'])->where('shop_id',$shopId)->find();
        if($dbCoin){
            $coin = $dbCoin['coin'];
        }

        $ret['state'] = 0;
        $ret['msg'] = "";
        $ret['goldNum'] = $coin;
        $ret['lockId'] = $user['id']."";
        $this->redis->set($mobile,$user['id'],15);


        echo json_encode($ret);
        die(-1);

    }

    public function extractGoldNumCheck()
    {
        $token = $this->request->param('token');
        $result = openssl_decrypt(base64_decode($token), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);

        $result = json_decode($result,true);
        $mobile = $result['userId'];
        $shopId = $result['shopId'];

        $isHave = $this->redis->get($mobile);
        $ret = array();
//        if(!$isHave){
//            $ret['state'] = 1;
//            $ret['msg'] = "缓存不存在不能提取";
//            echo json_encode($ret);
//            die(-1);
//        }
//        $cacheToken =  base64_encode(openssl_encrypt($isHave, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA));
//        if($cacheToken != $token) {
//            $ret['state'] = 1;
//            $ret['msg'] = "token不一致";
//
//            echo json_encode($ret);
//            die(-1);
//        }
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->find();

        $param = file_get_contents("php://input");

        $param = json_decode($param, true);
        $goldNum = $param['goldNum'];

        $userCoinModel =  new Usercoin();
        $dbCoin  = $userCoinModel->where('user_id',$user['id'])->where('shop_id',$shopId)->find();
        if($dbCoin){
            $coin = $dbCoin['coin'];
        }
        if($goldNum >$coin){
            $ret['state'] = 1;
            $ret['msg'] = "金币不足无法提取";
            $ret['goldNum'] = $coin;
            $ret['lockId'] = "-1";
            echo json_encode($ret);
            die(-1);
        }

        //用户锁 购买 和 提取出斥;
        $key = "check_gold_".$user['mobile'];

        if($this->redis->get($key)){

            $ret['state'] = 1;
            $ret['msg'] = "用户正在购买请勿提取";
            echo json_encode($ret);
            die(-1);
        }
        $this->redis->set($key,1,60);
        //释放同步锁
        $this->redis->rm($user['mobile']);
        if($goldNum>0){
             //    $userCoinOutModel->insert(['coin'=>$goldNum,'order_id'=>-1,'user_id'=>$user['id'],'create_time'=>time(),'type'=>'game','mark'=>'游戏提取扣除','shop_id'=>$shopId]);
            if($dbCoin){

                $userCoinModel->where('id',$dbCoin['id'])->setDec('coin',$goldNum);
            }
        }
        $this->redis->rm($key);
        $ret['state'] = 0;
        $ret['msg'] = "";
        echo json_encode($ret);
        die(-1);
    }

    public function settleGoldNum()
    {
        $token = $this->request->request('token');

        error_log("===token=1=".$token);


        $result = openssl_decrypt(base64_decode($token), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);

        $result = json_decode($result,true);


        //$goldNum = $this->request->param('goldNum');
        $param = file_get_contents("php://input");

        error_log("=======param====".json_encode($result));
        $param = json_decode($param, true);
        $goldNum = $param['goldNum'];

        $mobile = $result['userId'];
        $deviceId = $result['deviceId'];
        $captcha = $result['captcha'];
        $shopId = $result['shopId'];
        $isHave = $this->redis->get($mobile);
        $ret = array();
//        if(!$isHave){
//            $ret['state'] = 1;
//            $ret['msg'] = "缓存不存在不能提取";
//            $ret['goldNum'] = 0;
//            $ret['lockId'] = -1;
//            echo json_encode($ret);
//            die(-1);
//        }
//
//        error_log("===isHave==".$isHave);
//        $cacheToken =  base64_encode(openssl_encrypt($isHave, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA));
//        if($cacheToken != $token) {
//            $ret['state'] = 1;
//            $ret['msg'] = "token不一致";
//            $ret['goldNum'] = 0;
//            $ret['lockId'] = -1;
//            echo json_encode($ret);
//            die(-1);
//        }
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('mobile',$mobile)->find();

        $userCoinModel = new Usercoin();
        if($goldNum>0){
            //$userCoinModel->insert(['coin'=>$goldNum,'order_id'=>-1,'user_id'=>$user['id'],'create_time'=>time(),'mark'=>'游戏获取'.$deviceId,'shop_id'=>$shopId]);

            $dbCoin  = $userCoinModel->where('user_id',$user['id'])->where('shop_id',$shopId)->find();
            if($dbCoin){
                $userCoinModel->where('id',$dbCoin['id'])->setInc('coin',$goldNum);
            }

        }
        $this->redis->rm($user['mobile']);
        $ret['state'] = 0;
        $ret['msg'] = "";
        echo json_encode($ret);
        die(-1);

    }

}
